#include "floracommunitydevicemanger.h"
#include "FloraLogger.h"
FloraCommunityDeviceManger::FloraCommunityDeviceManger(QObject *parent) : QObject(parent)
{
    dev_count = 0;
}

void FloraCommunityDeviceManger::registerDecive(FloraCommunityDevice *dev,int addr )
{
    if(addr == 0)
    {
        dev_map.insert(dev_count,dev);
        dev->setMangerAddr(dev_count);
        connect(dev,&FloraCommunityDevice::sendBrustCommand,this,&FloraCommunityDeviceManger::SendBrustCommand);
    }
    else
    {
        dev_map.insert(addr,dev);
        dev->setMangerAddr(addr);
        connect(dev,&FloraCommunityDevice::sendBrustCommand,this,&FloraCommunityDeviceManger::SendBrustCommand);
    }

    dev_count++;
}

bool FloraCommunityDeviceManger::unregisterDecive(FloraCommunityDevice *dev)
{
    int ret = false;
    for (auto it = dev_map.begin(); it != dev_map.end(); )
    {
            if (it.value() == dev) {
                it = dev_map.erase(it); // erase会返回下一个迭代器
                disconnect(dev,&FloraCommunityDevice::sendBrustCommand,this,&FloraCommunityDeviceManger::SendBrustCommand);
                ret = true;
            } else {
                ++it; // 继续迭代
            }
    }
    return ret;
}

void FloraCommunityDeviceManger::registerBus(FloraCommunityBus *bus)
{
    m_bus = bus;
    connect(m_bus,&FloraCommunityBus::loopCommandResponse,this,&FloraCommunityDeviceManger::reciveData,Qt::QueuedConnection);
    connect(m_bus,&FloraCommunityBus::burstCommandResponse,this,&FloraCommunityDeviceManger::reciveBrustData,Qt::QueuedConnection);

}

void FloraCommunityDeviceManger::updateLoopCommand()
{
    QVector<commandTuple> commands;
    QMap<int, FloraCommunityDevice *>::iterator it;
    for (it = dev_map.begin(); it != dev_map.end(); ++it) {
        int key = it.key();
        FloraCommunityDevice *device = it.value();
        QMap<int,QByteArray> loopCommandMap = device->loopCommandMap;

        for (auto it = loopCommandMap.constBegin(); it != loopCommandMap.constEnd(); ++it) {
            int key = it.key();
            QByteArray value = it.value();
            commands.append(std::make_tuple(device->manger_addr, key, value));
        }
    }
    m_bus->updateLoopCommands(commands);
}

void FloraCommunityDeviceManger::SendBrustCommand(int manger_addr, int commandType, QByteArray da)
{
    // LOG_DEBUG<<"收到突发命令"<<commandType<<da.toHex(' ');
    auto commandTuple = std::make_tuple(manger_addr, commandType, da);
    m_bus->appendBurstCommand(commandTuple);

}

void FloraCommunityDeviceManger::reciveData(int manger_addr , int commandType , QByteArray da)
{
     if( dev_map.contains(manger_addr) )
     {
         dev_map[manger_addr]->setResponseData(commandType,da);
     }
}

void FloraCommunityDeviceManger::reciveBrustData(int manger_addr , int commandType , QByteArray da)
{

    if( dev_map.contains(manger_addr) )
    {

        dev_map[manger_addr]->setBrustResponseData(commandType,da);
    }
}
